1. 题目描述(中等难度)

[warning] 654. 最大二叉树

2. 解法一:深度优先搜索

获取数组的最大值索引,递归的保存最大值索引的值

class Solution {

    public TreeNode constructMaximumBinaryTree(int[] nums) {
        return maxTree(nums,0,nums.length-1);
    }

    //递归构造最大二叉树
    public TreeNode maxTree(int[] nums,int l,int r){
      if(l>r){
          return null;
      }
      int maxIndex = maxNumIndex(nums,l,r);
      TreeNode root = new TreeNode(nums[maxIndex]);
      root.left = maxTree(nums,l,maxIndex-1);
      root.right = maxTree(nums,maxIndex+1,r);
      return root;
    }

    //获取最大值索引
    public int maxNumIndex(int[] nums,int l,int r){
        Integer max = Integer.MIN_VALUE;
        int index = 0;
        for(int i=l;i<=r;i++){
            max = Math.max(max,nums[i]);
            if(max == nums[i]){
                index = i;
            }
        }
        return index;
    }

}
© gaohueric all right reserved,powered by Gitbook文件修订时间: 2021-12-08 23:22:22

results matching ""

    No results matching ""